import React, {  useEffect, useImperativeHandle, useRef, useState } from 'react';
import { intl } from '@/utils';
import TreeList, { Column } from 'devextreme-react/tree-list';
import notify from 'devextreme/ui/notify';
import PubSub from 'pubsub-js';
import SpinLoading from '../../../../SpinLoading';

import {  projectInfo } from '@/services/cpasRequest';
import './index.less';
const Zcbfpopup = React.forwardRef((props: any, ref: any) => {
    const [modalTableTreeData, setModalTableTreeData] = useState<any>([]); // 组成部分
    const [modalTableData, setModalTableData] = useState<any>( [{DBName:"1",XMType:"1"}]); // 项目信息
    const [fileAddress, setFileAddress] = useState<string>('');
    const [spinLoad, setSpinLoad] = useState<boolean>(false);
    const treeListRef = useRef<any>(); 

    const [treeType,settreetype]=useState<string>('null')
    useEffect(()=>{
        treeListRef.current.instance.selectAll()
        // console.log("dddd")
    },[modalTableTreeData])
    // 点击打开文件调用
    const  identifyEvents = async (fileAddress:string) => {
        if (fileAddress) {
            const res = await projectInfo( {filePath:fileAddress})                    
            if (res.ok) {
               
                setModalTableTreeData([...res.data.sjxm_Zcbf]); //  组成 部分
                setModalTableData(res.data.project_Info) // 项目信息
 
                
                
                // 判断是否是tree结构
                const  isTreeStructure=(arr:[])=> {
                    const ids = arr.map(item => item.id);
                    const parentIds = arr.filter(item => item.pzcbfID !== null).map(item => item.pzcbfID);
                  
                    if (new Set(ids).size !== ids.length) {
                      return 'null';
                    }
                  
                    for (const id of parentIds) {
                      if (!ids.includes(id)) {
                        return 'null';
                      }
                    }
                  
                    return 'pzcbfID';
                }

                // 判断组成部分是否是树形结构
        
                settreetype( isTreeStructure(res.data.sjxm_Zcbf.map(a=>{return {id:a.zcbfID,pzcbfID:a.pzcbfID}})))

                await PubSub.publish('importProjectPopupInfo', { msg: 'importProjectPopupInfoData', data: res.data.project_Info });
                setSpinLoad(false)
                setTimeout(async ()=>{
                    return await treeListRef.current.instance.selectAll()
                },500)
               
            } else {
                notify({ message: `导入项目失败`, position: 'top center' }, "error", 1000);
            }
        }


    }
    useImperativeHandle(ref, () => ({
        getSelectedRowsZcbfData: () => {
            treeListRef.current.instance.clearFilter();
            const tempdata = treeListRef.current.instance.getSelectedRowsData();
            const zcbfIDString = tempdata.map((item: any) => `'${item.zcbfID}'`).join(",");
            return {
                rowsData: tempdata,
                zcbfIDString,
                modalTableTreeData
            }
        },
        resetTreeList: () => {
            setModalTableTreeData([]);
            setFileAddress('');
        },
        getfileAddress:()=>{
            return fileAddress
        },
        // 给父组建传一次参数
        getmodalTableData:()=>{
            return modalTableData
        }
    }));

    return (
        <>
        {spinLoad && <SpinLoading></SpinLoading>}
        <TreeList
            ref={treeListRef}
            height={`calc(100%)`}
            className="zcbf"
            dataSource={modalTableTreeData}
            keyExpr="zcbfID"
            parentIdExpr={treeType}
            autoExpandAll={true}
            showColumnLines={true}
            allowColumnResizing={true}
            showBorders={true}
            columnMinWidth={100}
            columnResizingMode="widget"
            showRowLines={true}
            scrolling={{ rowRenderingMode: 'virtual' }}
            loadPanel={{ enabled: true }}
            searchPanel={{ width: 220, visible: true, placeholder: '' }}
            selection={{ mode: "multiple", allowSelectAll: true }}
            //fileaddress={{ width: 420, visible: false, placeholder: '' }}
            paging={{
                enabled: false
            }}
            toolbar={{
                items: [
                    {
                        location: 'before',
                        name:"fileaddress",
                        widget: 'dxTextBox',
                        options: {
                            mode: "url",
                            value: `数据文件: ${fileAddress}`,
                            title:"1"
                        },
                        text: ''
                    },
                    {
                        name: 'Buwwwwwtton',
                        location: 'after',
                        widget: 'dxButton',
                        options: {
                            text: "选择文件",
                            type: 'default',
                            onClick: async () => {
                                const result = await window.electronComponents.openDialog({
                                    properties: ['openFile'],
                                    filters: [{
                                        name: 'Aue Files',
                                        extensions: ["aue6"]
                                    }]

                                });

                                if (!result.canceled) {
                                    
                                    try {
                                        setFileAddress( result.filePaths[0]);
                                        setSpinLoad(true)
                                        await identifyEvents(result.filePaths[0])
                                    } catch (error) {
                                        notify({ message: `导入项目失败 ${error}`, position: 'top center' }, "error", 1000);
                                    }
                                }
                            }
                        }
                    },
                    {
                        name: 'searchPanel',
                        location: 'after',
                    }
                ]
            }}
        >
            <Column
                caption={intl('pro.TreeList.ComponentNumber', '组成部分编号')}
                dataField='zcbfID'
                width={180}
            />
            <Column
                caption={intl('pro.TreeList.ComponentName', '组成部分名称')}
                dataField='zcbfName'
            />

        </TreeList>
        </>
    );
})
export default Zcbfpopup;
